package com.lk.demo.controller;

import com.lk.demo.pojo.User;
import com.lk.demo.service.UserServcie;
import com.lk.demo.tools.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController//在每个方法上加@ResponseBody
@CrossOrigin//去掉跨域限制
public class UserJSONController {


    //查询
    @Autowired//注入
    UserServcie userServcie;
    //Controller->Servcie->Dao

    //查询user表
    @RequestMapping("userlistjson")
    public Result getAllUser(){
        return  Result.ok().put("data",userServcie.getAllUser());
    }


     @RequestMapping("addcommitjson")
        public Result addcommit(@RequestBody User user){
            int result= userServcie.addUser(user);
            if (result>0){
                return Result.ok();
            }
            return Result.error();
        }

    @RequestMapping("updateUserjson")
    public String updateUserjson(Model model,int id,int age,String name){
        model.addAttribute("id",id);
        model.addAttribute("age",age);
        model.addAttribute("name",name);
        return "updateuser.html";
    }

    @RequestMapping("updatecommitjson")
    public String updatecommitjson(User user){
        int result= userServcie.updateUser(user);
        if (result>0){
            return "redirect:/userlist";
        }
        return "fail.html";
    }

    @RequestMapping("loginjson")
    public Result loginjson(@RequestBody Map<String,String> map){
        String username=map.get("username");
        String password=map.get("password");
        //应该从数据库中验证
        if(username.equals("lk")&&password.equals("123456")){
            return  Result.ok();
        }
        return  Result.error();
    }

    @RequestMapping("searchjson/{name}")
    public Result searchjson(@PathVariable("name") String name){
        return Result.ok().put("data",userServcie.searchUserByName(name));
    }

    @RequestMapping("deleteUserByIdjson/{id}")
    public Result deleteUserByIdjson(@PathVariable("id") int id){
        return Result.ok().put("data",userServcie.deleteUserById(id));
    }

}
